import sensor, time, display
from pyb import UART

# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
lcd = display.SPIDisplay()

# 初始化串口
uart = UART(3, 115200)

# 颜色阈值和最小面积过滤
paper_threshold = (14, 45, 22, 122, -128, 127)
min_area = 100  # 根据场景调整

clock = time.clock()

while True:
    clock.tick()
    img = sensor.snapshot()
    blobs = img.find_blobs([paper_threshold])

    # 过滤小面积噪声
    valid_blobs = [b for b in blobs if b.pixels() > min_area]

    if valid_blobs:
        largest_blob = max(valid_blobs, key=lambda b: b.pixels())
        x, y = largest_blob.cx(), largest_blob.cy()
        area = largest_blob.pixels()

        # 绘制中心坐标和矩形
        img.draw_rectangle(largest_blob.rect(), color=(255, 0, 0))
        img.draw_cross(x, y, color=(255, 0, 0), size=10, thickness=2)

        # 发送中心坐标 + 面积（统一格式）
        data = f"{x},{y},{area}\n"
        uart.write(bytearray(data, 'utf-8'))  # 二进制编码
        print(x, y, area)  # 保持与串口一致

    else:
        uart.write(bytearray("-1,-1,0\n", 'utf-8'))  # 无效数据
        print("No blob")

    # 显示图像（可选）
    lcd.write(img)
